﻿using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using Devv.Core.Erroo;
using Devv.Core.Utils;

namespace Devv.Threeter
{
	static class MaintenanceManager
	{
		#region Properties

		static internal DateTime LastCheck { get; set; }
		static internal String LatestVersion { get; set; }

		static internal String InstalledVersion
		{
			get
			{
				return AssemblyUtil.GetFriendlyVersion(Assembly.GetEntryAssembly());
			}
		}

		#endregion

		#region Upgrade

		public static void UpgradeFromPrevious()
		{
			String version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
			String dataPath = Application.UserAppDataPath.Replace(version, String.Empty);
			String[] folders = Directory.GetDirectories(dataPath);

			try
			{
				for (Int32 i = 0; i < folders.Length; i++)
				{
					if (!folders[i].Contains(version))
					{
						String[] files = Directory.GetFiles(folders[i]);

						for (Int32 f = 0; f < files.Length; f++)
						{
							File.Move(files[f], Application.UserAppDataPath + "\\" + Path.GetFileName(files[f]));
						}
					}
				}
			}
			catch (Exception ex)
			{
				ErrorHandler.Handle(ex, "Could not fully upgrade from previous versions.");
			}
		}

		#endregion

		#region Cleanup

		internal static void Cleanup()
		{
			String version = Assembly.GetExecutingAssembly().GetName().Version.ToString();
			String dataPath = Application.UserAppDataPath.Replace(version, String.Empty);
			String[] folders = Directory.GetDirectories(dataPath);

			for (Int32 i = 0; i < folders.Length; i++)
			{
				if (!folders[i].Contains(version))
				{
					DirectoryInfo dir = new DirectoryInfo(folders[i]);

					if (dir.CreationTime.AddMonths(6) < DateTime.Now)
					{
						try
						{
							dir.Delete(true);
						}
						catch (Exception ex)
						{
							ErrorHandler.Handle(ex, "Could not run the cleanup procedure.");
						}
					}
				}
			}
		}

		#endregion

		#region Check for updates

		internal static void CheckUpdates()
		{
			ThreadPool.QueueUserWorkItem(CheckUpdatesAsync);

			LastCheck = DateTime.Now;
		}

		internal static void CheckUpdatesAsync(Object obj)
		{
			try
			{
				WebClient client = new WebClient();
				LatestVersion = client.DownloadString(GlobalMessages.AppUrl + "Version.txt");
			}
			catch (Exception ex)
			{
				ErrorHandler.Handle(ex, "Could not check for updated versions online.");
				LatestVersion = InstalledVersion;
			}
		}

		internal static Boolean HasNewVersion()
		{
			if (!String.IsNullOrEmpty(LatestVersion))
			{
				String installed = InstalledVersion.Replace(".", String.Empty);
				String latest = LatestVersion.Replace(".", String.Empty);

				return Convert.ToInt32(installed.Substring(0, 3)) < Convert.ToInt32(latest.Substring(0, 3));
			}

			return false;
		}

		#endregion

		#region Helper methods

		internal static void DownloadLatest()
		{
			Process.Start(GlobalMessages.AppUrl + "Download.aspx");
		}

		#endregion
	}
}